<?php
// Basically, an associative array that knows when it's been modified,
// can revert to its unmodified state, or commit to its new state
class SmartArray {
    private $data;   // the array containing the original values
    protected $modified = array();  // the array containing the new values
    private $is_modified = false;
    
    public function __construct($array) {
        assert('is_array($array)');
        $this->data = $array;
    }
            
    public function set($field,$val) {
        if ( !isset($this->data[$field]) || ($this->data[$field] !== $val) ) {
            $this->modified[$field] = $val;
            $this->is_modified = true;
        }
    }

    public function set_array($array) {
        foreach ($array as $field=>$val) {
            $this->set($field,$val);
        }
    }
    
    public function get($field) {
        if ( isset($this->modified[$field]) ) return $this->modified[$field];
        elseif ( isset($this->data[$field]) ) return $this->data[$field];
        else return null;
    }
    
    public function get_array() {
        return array_merge($this->data,$this->modified);
    }
    
    public function is_modified() {
        return $this->is_modified;
    }
    
    public function commit() {
        $this->data = array_merge($this->data,$this->modified);
        $this->revert();
    }
    
    public function revert() {
        $this->modified = array();
        $this->is_modified = false;
    }
}

?>